import socket
import os
class FileReceiver:
    def __init__(self,ip,port,savePath):
        print("fileReceiver init")
        self.port = port
        self.savePath = savePath
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((ip,self.port))
        while True:
            print("receiver begin listening on port:%d"%self.port)
            self.s.listen(1)
            self.sender,self.senderAddr = self.s.accept()
            print("senderAddr:",self.senderAddr)
            while True:
                res = self.receive(10240)
                if res=="disconnect":
                    break

    
    def receive(self,length):
        print("a new receive loop")
        ###等待对方发送文件名
        filename = ""
        while True:
            data = self.sender.recv(length)
            # print("1:",data)
            if not data == b'' and not data==b'disconnect':
                filename = data.decode('utf-8')
                break
            if data == b'disconnect':
                return 'disconnect'
        print("filename: ", filename)
        ###返回文件名接收成功
        self.sender.send("filename ok".encode("utf-8"))
        ###开始文件接受
        try:
            os.remove(self.savePath+filename)
        except OSError:
            pass
        myfile = open(self.savePath+filename,"ab")
        # resBytes = b""
        while True:
            data = self.sender.recv(length)
            if data==b'':
                break
            if data==b'file send finish!':
                break
            # print("recv:",data)
            myfile.write(data)
            self.sender.send("receive ok".encode("utf-8"))
        print("file receive finish!")
        myfile.close()


if __name__ == "__main__":
    myFileReceiver = FileReceiver(ip="127.0.0.1",port=913,savePath="./")
    myFileReceiver.receive(10240)
        